<?php
/**
 * Created by PhpStorm.
 * User: ZSYK
 * Date: 2015/12/8
 * Time: 16:44
 */

namespace Icsoc\DataBundle\Model;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Icsoc\CoreBundle\Logger\ActionLogger;

/**
 * Class BusinessGroupModel
 *
 * @package Icsoc\DataBundle\Model
 */
class BusinessGroupModel
{
    /** @var \Doctrine\DBAL\Connection */
    private $conn;
    private $logger;

    /**
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->conn = $this->container->get('doctrine.dbal.default_connection');
        $this->logger = $this->container->get('logger');
    }

    /**
     * @param array $param
     *
     * @return array
     */
    public function listBusinessGroup($param = array())
    {
        $vccId = isset($param['vcc_id']) ? $param['vcc_id'] : '';
        $page = isset($param['page']) ? $param['page'] : 1;
        $rows = isset($param['rows']) ? $param['rows'] : 10;
        $order = isset($param['order']) ? $param['order'] : 'desc';
        $field = isset($param['field']) ? $param['field'] : 'group_id';
        $groupName = isset($param['group_name']) ? $param['group_name'] : '';

        if (empty($vccId)) {
            return array('code' => 402, 'message' => '企业ID不能为空');
        }

        $where = " is_del=0 AND vcc_id=$vccId ";
        if (!empty($groupName)) {
            $where .= " AND group_name like '%$groupName%' ";
        }

        $authority = $this->container->get("icsoc_core.common.class")->getUserTypeCondition();
        if (!empty($authority['group_id'])) {
            $where .= " AND group_id in (".implode(',', $authority['group_id']).")";
        }

        $start = $rows * $page - $rows;
        $start = $start > 0 ? $start : 0;

        try {
            $count = $this->conn->fetchColumn("SELECT COUNT(*) FROM win_group WHERE $where");
            $data = $this->conn->fetchAll(
                "SELECT group_id,group_name,vcc_id
                FROM win_group
                WHERE {$where}
                ORDER BY {$field} {$order}
                LIMIT {$start},{$rows}"
            );
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());

            return array('code' => 400, 'message' => '数据库执行错误');
        }

        return array(
            'code' => 200,
            'message' => 'success',
            'records' => $count,
            'page' => $page,
            'total' => ceil($count / $rows),
            'rows' => $data,
        );
    }

    /**
     * @param int    $vccId
     * @param string $groupName
     *
     * @return array
     */
    public function addBusinessGroup($vccId = 0, $groupName = '')
    {
        if (empty($vccId)) {
            return array('code' => 401, 'message' => '企业ID不能为空');
        }
        if (empty($groupName)) {
            return array('code' => 402, 'message' => '业务组名称不能为空');
        }
        $rst = $this->checkBusinessGroup($vccId, $groupName, 0);

        if ($rst['code'] != 200) {
            return $rst;
        }

        try {
            $this->conn->insert('win_group', array('vcc_id' => $vccId, 'group_name' => $groupName));
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());

            return array('code' => 400, 'message' => '数据库执行错误');
        }

        /** 记录系统操作日志 */
        $content = $this->container->get('translator')
            ->trans(
                "Add Business Group %groupName%",
                array('%groupName%' => $groupName)
            );

        $this->container->get("icsoc_core.helper.logger")->actionLog(ActionLogger::ACTION_ADD, $content);

        return array('code' => 200, 'message' => 'success');
    }

    /**
     * @param int    $id
     * @param string $groupName
     * @param int    $vccId
     *
     * @return array
     */
    public function editBusinessGroup($id = 0, $groupName = '', $vccId = 0)
    {
        if (empty($id)) {
            return array('code' => 401, 'message' => 'ID不能为空');
        }
        if (empty($groupName)) {
            return array('code' => 402, 'message' => '业务组名称不能为空');
        }
        $rst = $this->checkBusinessGroup($vccId, $groupName, $id);

        if ($rst['code'] != 200) {
            return $rst;
        }

        try {
            $name = $this->conn->fetchColumn(
                'SELECT group_name FROM win_group WHERE group_id = :group_id',
                array('group_id' => $id)
            );
            $this->conn->update('win_group', array('group_name' => $groupName), array('group_id' => $id));
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());

            return array('code' => 400, 'message' => '数据库执行错误');
        }

        /** 记录系统操作日志 */
        $logStr = sprintf('group_name:%s=>%s', $name, $groupName);
        $content = $this->container->get("translator")->trans(
            "Update Business Group %str%",
            array('%str%' => $logStr)
        );

        $this->container->get("icsoc_core.helper.logger")->actionLog(ActionLogger::ACTION_UPDATE, $content);

        return array('code' => 200, 'message' => 'success');
    }

    /**
     * @param string $ids
     * @param int    $vccId
     *
     * @return array
     * @throws \Doctrine\DBAL\ConnectionException
     */
    public function deleteBusinessGroup($ids = '', $vccId = 0)
    {
        if (empty($ids)) {
            return array('code' => 401, 'message' => 'ID不能为空');
        }
        if (empty($vccId)) {
            return array('code' => 402, 'message' => '企业ID不能为空');
        }

        $idArr = explode(',', $ids);
        $this->conn->beginTransaction();
        $error = 0;

        try {
            foreach ($idArr as $id) {
                $this->conn->update('win_group', array('is_del' => 1), array('group_id' => $id));
                $this->conn->update('win_agent', array('group_id' => 0), array('group_id' => $id, 'vcc_id' => $vccId));
            }
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());
            $error++;
        }

        if (!empty($error)) {
            $this->conn->rollBack();

            return array('code' => 400, 'message' => '数据库执行错误');
        }

        $this->conn->commit();

        /** 记录系统操作日志 */
        $logStr = $this->container->get('translator')->trans(
            'Delete Business Group %str%',
            array('%str%' => $ids)
        );
        $this->container->get("icsoc_core.helper.logger")->actionLog(ActionLogger::ACTION_DELETE, $logStr);

        return array('code' => 200, 'message' => '删除成功');
    }

    /**
     * 批量分配业务组
     *
     * @param array $param
     *
     * @return array|string
     */
    public function allotAgentBusinessGroup($param)
    {
        $vccId = empty($param['vcc_id']) ? 0 : $param['vcc_id'];
        $groupId = empty($param['group_id']) ? 0 : $param['group_id'];
        $agents = empty($param['ids']) ? array() : $param['ids'];
        $actionFlag = empty($param['flag']) ? 1 : $param['flag'];
        if (empty($vccId)) {
            return array('code' => 401, 'message' => '企业ID为空');
        }

        //验证业务组id 是否属于该企业；
        if (!empty($groupId)) {
            try {
                $rst = $this->conn->fetchColumn("SELECT group_id FROM win_group WHERE group_id=$groupId AND vcc_id=$vccId AND is_del=0");
            } catch (\Exception $e) {
                $this->logger->error($e->getMessage());

                return array('code' => 400, 'message' => '数据库操作失败');
            }
            if (empty($rst)) {
                return array('code' => 402, 'message' => '业务组不属于该企业');
            }
        } else {
            return array('code' => 403, 'message' => '业务组ID为空');
        }

        if (empty($agents)) {
            return array('code' => 404, 'message' => 'ids参数为空');
        }
        $username = $this->container->get('security.token_storage')->getToken()->getUsername();
        $ip = $this->container->get('request')->getClientIp();
        $address = $this->container->get('icsoc_core.common.class')->newGetWinIp();
        $port = $this->container->getParameter('win_socket_port');
        try {
            foreach ($agents as $v) {
                if ($actionFlag == 1) {
                    $this->conn->update('win_agent', array('group_id' => $groupId), array('id' => $v, 'vcc_id' => $vccId));
                } else {
                    $this->conn->update('win_agent', array('group_id' => 0), array('id' => $v, 'vcc_id' => $vccId));
                }
                //添加完成之后，重载坐席
                $this->container->get('icsoc_data.validator')->reloadAgent($vccId, $address, $v, $port);
            }
            $this->container->get('icsoc.manage.logger')->info(
                sprintf(
                    "用户【%s:%s】将企业【%s】下的坐席【%s】【%s】到业务组【%s】",
                    $username,
                    $ip,
                    $vccId,
                    json_encode($agents),
                    $actionFlag == 1 ? '分配' : '取消分配',
                    $groupId
                )
            );
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());

            return array('code' => 400, 'message' => '数据库操作失败');
        }

        return array("code" => 200, 'message' => 'success');
    }

    /**
     * 获取业务组
     *
     * @param int $vccId
     *
     * @return array
     */
    public function getGroupsBusinessGroup($vccId = 0)
    {
        if (empty($vccId)) {
            return array('code' => 401, 'message' => '企业ID不能为空');
        }

        try {
            $result = $this->conn->fetchAll("SELECT group_id,group_name FROM win_group WHERE vcc_id=$vccId AND is_del=0");
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());

            return array('code' => 400, 'message' => '数据库执行错误');
        }
        $groups = array();
        foreach ($result as $v) {
            $groups[$v['group_id']] = $v['group_name'];
        }

        return array('code' => 200, 'message' => 'success', 'data' => $groups);
    }

    /**
     * 检测业务组名称是否存在
     *
     * @param int    $vccId
     * @param string $groupName
     * @param int    $id
     *
     * @return array
     */
    public function checkBusinessGroup($vccId = 0, $groupName = '', $id = 0)
    {
        if (empty($vccId)) {
            return array('code' => 401, 'message' => '企业ID不能为空');
        }
        if (empty($groupName)) {
            return array('code' => 402, 'message' => '业务组名称不能为空');
        }

        try {
            $result = $this->conn->fetchAll(
                "SELECT * FROM win_group WHERE vcc_id=$vccId AND group_name='$groupName' AND group_id<>$id AND is_del=0"
            );
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());

            return array('code' => 400, 'message' => '数据库执行错误');
        }
        if (!empty($result)) {
            return array('code' => 403, 'message' => '业务组名称已存在');
        }

        return array('code' => 200, 'message' => 'success');
    }
}
